/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.logical.allhit.gui.action;

import com.logical.allhit.Kernel;
import com.logical.allhit.setting.Account;
import com.logical.allhit.setting.Setting;
import com.logical.allhit.util.MsgLogger;
import java.awt.Event;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.KeyStroke;

/**
 *
 * @author Sanjeet Jha
 */
public class ExprotCSVAction extends AbstractAction {
    

    public ExprotCSVAction() {
        putValue(NAME, bundle.getString("csv.name"));
        putValue(SHORT_DESCRIPTION, bundle.getString("csv.shortdis"));
        putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_3, Event.CTRL_MASK));
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        try {
            JFileChooser jfc = new JFileChooser(System.getProperty("user.home"));
            int value = jfc.showSaveDialog(Kernel.getInstance().getFrame());
            if (value == JFileChooser.APPROVE_OPTION) {
                File file = jfc.getSelectedFile();
                generateCsvFile(file);
                MsgLogger.getInstance().showMsg("Save CSV File");
            }
        } catch (Exception ex) {
            Logger.getLogger(ProxySettingAction.class.getName()).log(Level.WARNING, ex.getMessage(), ex);
        }
    }

    
    private void generateCsvFile(File file) {
        try {
            FileWriter writer = new FileWriter(file, false);
            ArrayList<Account> accounts = Setting.getInstance().getAccounts();
            
            writer.append("Name, user type, uid,left child, right child, total child, last Update Date, balance\n");
            
            for (Account account : accounts) {
                writer.append(account.getName()+",");
                writer.append(account.getUsertype()+",");
                writer.append(account.getUid()+",");
                writer.append(account.getLeftchild()+",");
                writer.append(account.getRightchild()+",");
                writer.append(account.getTotalchild()+",");
                writer.append(account.getLastUpdateDate()+",");
                writer.append(account.getBalance()+"");
                writer.append('\n');
            }

            //generate whatever data you want

            writer.flush();
            writer.close();
        } catch (IOException e) {
            Logger.getLogger(ExprotCSVAction.class.getName()).log(Level.WARNING, e.getMessage(), e);
        }
    }
}
